package com.example.certificate.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.certificate.dto.*;
import com.example.certificate.dto.common.DelByIdDto;
import com.example.certificate.entity.OrgUser;
import com.example.certificate.entity.User;
import com.example.certificate.execption.BusinessException;
import com.example.certificate.mapper.UserMapper;
import com.example.certificate.service.CodeService;
import com.example.certificate.service.OrgUserService;
import com.example.certificate.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.certificate.utils.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户登陆信息数据表 服务实现类
 * </p>
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);

    @Resource
    private RedisTemplateUtil redisTemplateUtil;

    @Autowired
    private CodeService codeService;

    @Resource
    private UserMapper userMapper;

    @Autowired
    private OrgUserService orgUserService;

    @Override
    public String login(LoginDTO dto) throws BusinessException {
        User user = null;
        if(dto.getLoginStatus()){
            user = authUserData(dto,true);
        }else {
            user = authUserData(dto,false);
        }
        String token = JWTUtil.sign(user.getPhone(), JSONObject.toJSONString(user));
        redisTemplateUtil.setValExpire(token,JSONObject.toJSONString(user),2, TimeUnit.HOURS);
        return token;
    }

    /**
     * @Description  校验用户数据
     * @Param [dto]
     * @return common.projects.develop.entity.OrgUser
     **/
    public User authUserData(LoginDTO dto,Boolean status) throws BusinessException {
        User user = null;
        if(status){
            user = userMapper.selectOne(new QueryWrapper<User>().eq("phone",dto.getUsername()).eq("pwd",dto.getPassword()));
        }else {
            user = userMapper.selectOne(new QueryWrapper<User>().eq("email",dto.getUsername()).eq("pwd",dto.getPassword()));
        }
        if(user == null) throw new BusinessException(ResultConstant.NO_EXIST.resultCode,"用户不存在，请稍后重试");
        if(user.getStatus() == 0) throw new BusinessException(ResultConstant.USER_DISABLE.resultCode, "用户被禁用，请联系管理员");
        return user;
    }



    /**
     * @Description  发送验证码接口
     * @Param [dto]
     * @return void
     **/

    @Override
    public String sendSms(SendSmsDTO dto) throws ClientException, BusinessException {
        SendSmsResponse sms_203185877 = codeService.sendSms(dto.getPhone(), "SMS_203185877", 4);
        return sms_203185877.getMessage();
    }


    @Override
    public void updatePass(UpdatePassDto dto) throws BusinessException {
        //检验验证码
        codeService.checkMobile(dto.getPhone(), dto.getCode(), 4);
        if(dto.getPassword().equals(dto.getNewPass())){
            userMapper.updatePass(dto.getPhone(),dto.getPassword());
        }else {
            throw new BusinessException(ResultConstant.IS_EXIST.resultCode,"密码不一致，请稍后重试！");
        }
    }


    @Override
    public void registerInfo(RegisterDto dto) throws BusinessException {
        Boolean aBoolean = false;
        try{
            aBoolean = checkUserExists(dto.getPhone(), dto.getEmail());
            if(aBoolean == true) throw  new BusinessException(ResultConstant.IS_EXIST.resultCode,"用户已存在");
            if(dto.getPassword().equals(dto.getNewPassword())){
                User user = insertUser(dto);
                if(user != null){
                    dto.setId(user.getId());
                    orgUserService.insertOrgUser(dto);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }


    @Override
    public void perfectData(PerfectInfoDto dto) {
        Boolean userExists = false;
        try{
            userExists = checkUserExists(dto.getPhone(), dto.getEmail());
            if(userExists){
               orgUserService.perfectUserData(dto);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public ResultEntity delByUserId(DelByIdDto dto) {
        if(userMapper.deleteById(dto.getId()) > 0){
            return new ResultEntity();
        }
        return new ResultEntity(ResultConstant.DELETE_FAIL);
    }

    @Override
    public ResultEntity updateUserInfo(OrgUser dto) {
        Boolean aBoolean = orgUserService.updateOrgUser(dto);
        return aBoolean == true ? new ResultEntity() : new ResultEntity(ResultConstant.OPERATE_FAIL);
    }

    @Override
    public ResultEntity selBaseInfo(String userId) {
        return new ResultEntity(orgUserService.getUserBase(userId));
    }

    @Override
    public ResultEntity updateUserRole(ManagementDto dto) {
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("id",dto.getId()));
        user.setRoleId(dto.getRole());
        return userMapper.updateById(user) > 0 ? new ResultEntity("操作成功") : new ResultEntity(ResultConstant.OPERATE_FAIL);
    }

    @Override
    public ResultEntity insertUser(InsertRegisterDto dto) throws BusinessException {
        //检验验证码
      //  codeService.checkMobile(dto.getPhone(), dto.getCode(), 4);
        User phone = userMapper.selectOne(new QueryWrapper<User>().eq("phone", dto.getPhone()));
        if(phone != null){
            throw new BusinessException(ResultConstant.IS_EXIST.resultCode,"用户已存在");
        }

        User user = new User();
        user.setPwd(dto.getPassword());
        user.setPhone(dto.getPhone());
        user.setEmail(dto.getEmail());
        user.setRoleId(dto.getIdentityCard());
        userMapper.insert(user);

        OrgUser orgUser = new OrgUser();
        orgUser.setEmail(dto.getEmail());
        orgUser.setGender(dto.getGender());
        orgUser.setImage(dto.getImage());
        orgUser.setName(dto.getName());
        orgUser.setNickname(dto.getNickname());
        orgUser.setIdentityCard(dto.getIdentityCard());
        orgUser.setPhone(dto.getPhone());
        orgUser.setId(user.getId());
        orgUserService.save(orgUser);

        return new ResultEntity();
    }

    @Override
    public ResultEntity updateStatus(UpdateStatusDTO dto) {
        User user = new User();
        user.setStatus(dto.getStatus());
        user.setId(dto.getId());
        userMapper.updateById(user);
        return new ResultEntity(user);
    }


    public Boolean checkUserExists(String phone,String email){

        User phoneUser = userMapper.selectOne(new QueryWrapper<User>().eq("phone",phone));
        if(phoneUser != null)
            return true;

        User emailUser = userMapper.selectOne(new QueryWrapper<User>().eq("email",email));
        if(emailUser != null)
            return true;

        return false;
    }


    public User insertUser(RegisterDto dto){
        User user = new User();
        BeanUtils.copyProperties(dto,user);
        user.setPwd(dto.getPassword());
        userMapper.insert(user);
        return user;
    }
}
